<template>
  <section class="author">
    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100">
      <FormItem label="文章标题" prop="title">
        <Input v-model="formValidate.title" placeholder="文章标题"></Input>
      </FormItem>
      <!-- <FormItem label="文章作者" prop="author">
        <Input v-model="formValidate.author" placeholder="文章作者"></Input>
      </FormItem> -->
      <FormItem label="文章简介" prop="description">
        <Input v-model="formValidate.description" placeholder="文章简介"></Input>
      </FormItem>
      <FormItem label="文章关键字" prop="keyword">
        <Input v-model="formValidate.keyword" placeholder="文章简介"></Input>
      </FormItem>
      <FormItem label="文章图片">
        <img :src="formValidate.cover" style="width:100%">
        <Upload
            ref="upload"
            :show-upload-list="false"
            :default-file-list="defaultList"
            :on-success="uploadSuccess"
            v-if="!formValidate.cover"
            :format="['jpg','jpeg','png']"
            :max-size="2048"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            :before-upload="handleBeforeUpload"
            multiple
            type="drag"
            action="http://localhost:3000/api/v1/upload"
            style="display: inline-block;width:58px;">
            <div style="width: 58px;height:58px;line-height: 58px;">
                <Icon type="ios-camera" size="20"></Icon>
            </div>
        </Upload>
      </FormItem>
      <FormItem label="文章分类">
        <Select v-model="formValidate.category_id">
          <Option v-for="(item, index) in categoryList" :value="item.id" :key="index">{{item.name}}</Option>
        </Select>
      </FormItem>
      <FormItem label="文章内容" prop="content">
        <mavon-editor
          v-model="formValidate.content"
          :ishljs="true"
          style="z-index:0;box-shadow: rgba(0, 0, 0, 0.1) 0px 2px 12px 0px !important;"
          ref=md>
        </mavon-editor>

      </FormItem>
      <FormItem>
        <Button @click="handleReset('formValidate')">重置</Button>
        <Button type="primary" @click="handleSubmit('formValidate')" style="margin-left: 8px">提交</Button>
      </FormItem>
    </Form>
    <Modal title="View Image" v-model="visible">
        <img :src="url" v-if="visible" style="width: 100%">
    </Modal>
  </section>
</template>
<script>
import category from '../../api/category'
import user from '../../api/articles'
  export default {
    data() {
      return {
        token: '',
        id: this.$route.params.id,
        detail: null,
        categoryList: [],
        formValidate: {
          title: '',
          author: localStorage.nickname,
          category_id: '',
          cover: '',
          description: '',
          keyword: '',
          content: '',
          user_id: localStorage.userid
        },
        ruleValidate: {
          title: [
            {required: true, message: '文章标题不能为空', trigger: 'blur'}
          ],
          author: [
            {required: true, message: '文章作者不能为空', trigger: 'blur'}
          ],
          description: [
            {required: true, message: '文章简介不能为空', trigger: 'blur'}
          ],
          keyword: [
            {required: true, message: '文章关键字不能为空', trigger: 'blur'}
          ],
          content: [
            {required: true, message: '文章内容不能为空', trigger: 'blur'}
          ]
        },
        uploadList: [],
        defaultList: [],
        visible: false,
        url: ''
      }
    },
    mounted() {
      this._getCategoryList();
    },
    methods: {

      handleView (name) {
          this.url = name;
          this.visible = true;
      },
      handleRemove (file) {
          const fileList = this.$refs.upload.fileList;
          this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
      },
      handleFormatError (file) {
          this.$Notice.warning({
              title: 'The file format is incorrect',
              desc: 'File format of ' + file.name + ' is incorrect, please select jpg or png.'
          });
      },
      handleMaxSize (file) {
          this.$Notice.warning({
              title: 'Exceeding file size limit',
              desc: 'File  ' + file.name + ' is too large, no more than 2M.'
          });
      },
      handleBeforeUpload () {
          const check = this.uploadList.length < 5;
          if (!check) {
              this.$Notice.warning({
                  title: 'Up to five pictures can be uploaded.'
              });
          }
          return check;
      },
      handleRemove (file) {
          const fileList = this.$refs.upload.fileList;
          this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
      },
      // 上传图片成功
      uploadSuccess({path}) {
        let srt = path.replace('/public','')
        let url = `http://127.0.0.1:3000${srt}`
        console.log(url)
        this.$set(this.formValidate,'cover',url)
      },
      // 上传图片失败
      uploadError(response) {
        this.$Message.error('上传失败!');
        console.log(response)
      },
      preview(file) {
        console.log(file)
      },
      // 获取分类列表
      async _getCategoryList() {
          try{ 
              const { data :res } = await category.list({})
              if(res.code !== 200) return this.$Message.error(res.msg)
              this.categoryList = res.data
          }catch(e){
              console.log(e);
          }
      },
      // 创建
      async _createArticle() {
        this.formValidate.id = this.id;
        this.formValidate.user_id = localStorage.userid
        try {
          await this.createArticle(this.formValidate);
          this.$Message.success('新增成功!');
          this.$router.push('/article');

        } catch (e) {

        }
      },
      // 提交
      handleSubmit(name) {
        this.$refs[name].validate(async (valid) => {
            if(!valid) return false
            const { data : res } = await user.create({
                ...this.formValidate,
            })
            console.log(res);
            if(res.code !== 200 ) return this.$Message.error(res.msg)
            this.$Message.success('创建成功')
            this.formValidate = { 
                title: '',
                author: localStorage.nickname,
                category_id: '',
                cover: '',
                description: '',
                keyword: '',
                content: ''
            }
            this.$router.push('/article-list')
        })
      },
      handleReset(name) {
        this.$refs[name].resetFields();
      }
    }
  }
</script>
<style scoped lang="less">
  .author {
    box-sizing: border-box;
    width: @window-Width;
    min-height: 80vh;
    margin: 24px auto;
    overflow: hidden;
    background-color: #fff;
    border-radius: 6px;
    padding: 24px;
  }
  .article-cover {
    width: 120px;
  }

  .article-cover img {
    width: 100%;
  }

  .cover {
    display: flex;
  }

  .cover .upload {
    width: 280px;
    margin-right: 32px;
  }
    .demo-upload-list{
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0,0,0,.2) !important;
        margin-right: 4px;
    }
    .demo-upload-list img{
        width: 100%;
        height: 100%;
    }
    .demo-upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.6);
    }
    .demo-upload-list:hover .demo-upload-list-cover{
        display: block;
    }
    .demo-upload-list-cover i{
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
</style>
